const userModel = appRequire('models/user');
const artPPTModel = appRequire('models/artPPT');
const orderModel = appRequire('models/order');
const wxConfig = appRequire('config');

const crypto = require("crypto");

var request = require('request');
var xmlreader = require("xmlreader");
var wxMiniPayUnits = appRequire('common/wx/wxMiniPayUnits');

//var wxurl = "https://j12u7fb6o1.52http.tech/wx/wxNotice"//通知地址测试
var wxurl = "https://newartapi.jimuzhou.cloud/wx/wxNotice"//通知地址正式

module.exports = {
    getSession,
    wxPay,
    wxH5Pay,
    checkOrder
};


//微信支付
async function wxH5Pay(req, thisResponse) {
    //首先拿到前端传过来的参数
    let postData = req.body;
    let orderCode = postData.orderCode;
    let money = postData.money;
    let CODE = postData.code;
    let appid = "wx65a30b3ef4afe860"
    let appsecret = "1bd2ea37caa09e2c60bbb433bb5333b6"
    let mchid = "1600766491"
    let mchkey = "xrXR1234567891234567891234567891"


    let thisUser = await userModel.user.findOne({
        where: {
            objectId: postData.uid
        }
    })
    let openid = thisUser.wcMiniId

    //console.log('APP传过来的参数是', orderCode + '----' + money + '------'  + '----' + appid + '-----' + appsecret + '-----' + mchid + '-----' + mchkey);

    //首先生成签名sign
    // appid
    let mch_id = mchid;
    let nonce_str = wxMiniPayUnits.createNonceStr();
    let timestamp = wxMiniPayUnits.createTimeStamp();
    let body = '美术课件云助手';
    let out_trade_no = orderCode;
    let total_fee = wxMiniPayUnits.getmoney(money);
    let spbill_create_ip = req.connection.remoteAddress; // 支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP
    let notify_url = wxurl;
    let trade_type = 'JSAPI';  // 'APP';公众号：'JSAPI'或'NATIVE'

    let sign = wxMiniPayUnits.paysignjsapi(appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type, mchkey);

    // console.log('sign==', sign);

    //组装xml数据
    var formData = "<xml>";
    formData += "<appid>" + appid + "</appid>";  //appid
    formData += "<body><![CDATA[" + "美术课件云助手" + "]]></body>";
    formData += "<mch_id>" + mch_id + "</mch_id>";  //商户号
    formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串，不长于32位。
    formData += "<notify_url>" + notify_url + "</notify_url>";
    formData += "<openid>" + openid + "</openid>";
    formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";
    formData += "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>";
    formData += "<total_fee>" + total_fee + "</total_fee>";
    formData += "<trade_type>" + trade_type + "</trade_type>";
    formData += "<sign>" + sign + "</sign>";
    formData += "</xml>";

    //console.log('formData===', formData);

    var url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

    request({ url: url, method: 'POST', body: formData }, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            console.log(body);

            xmlreader.read(body.toString("utf-8"), async function (errors, response) {
                if (null !== errors) {
                    console.log(errors)
                    return;
                }
                console.log('长度===', response.xml.prepay_id.text().length);
                var prepay_id = response.xml.prepay_id.text();
                console.log('解析后的prepay_id==', prepay_id);


                //将预支付订单和其他信息一起签名后返回给前端
                let package = "prepay_id=" + prepay_id;
                let signType = "MD5";
                let minisign = wxMiniPayUnits.paysignjsapimini(appid, nonce_str, package, signType, timestamp, mchkey);

                //创建单据
                let course = await artPPTModel.findOne({
                    where: {
                        objectId: postData.pptId
                    },
                })
                course = Common.clone(course)
                if (course) {
                    await orderModel.order.create({
                        objectId: sid.uuid(),
                        out_trade_no: out_trade_no,
                        status: 0,
                        pptId: postData.pptId,
                        payMoney: Number(money),
                        storeMoney: (Number(money) * 0.8),
                        sellerId: course.userId,
                        buyerId: postData.uid,
                        type: 1,
                    })

                    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
                    returnData.data = {
                        'appId': appid,
                        'partnerId': mchid,
                        'prepayId': prepay_id,
                        'nonceStr': nonce_str,
                        'timeStamp': timestamp,
                        'package': 'Sign=WXPay',
                        'paySign': minisign,
                    }
                    return thisResponse.json(returnData);
                }

            });
        }
    });
}

//微信支付
async function wxPay(req, thisResponse) {
    //首先拿到前端传过来的参数
    let postData = req.body;
    let orderCode = postData.orderCode;
    let money = postData.money;
    let CODE = postData.code;
    let appid = wxConfig['wxMini' + postData.source].appId
    let appsecret = wxConfig['wxMini' + postData.source].secret
    let mchid = wxConfig['wxMini' + postData.source].mchid
    let mchkey = wxConfig['wxMini' + postData.source].mchkey

    let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + appsecret + '&js_code=' + CODE + '&grant_type=authorization_code'
    return request({ url: url, method: 'GET' }, async function (err, res, result11) {
        console.log("测试错误", result11)
        result11 = JSON.parse(result11);

        let openid;
        if (result11 && result11.openid) {
            openid = result11.openid
        }
        else {
            let thisUser = await userModel.user.findOne({
                where: {
                    objectId: postData.uid
                }
            })
            openid = thisUser.wcMiniId
        }

        //console.log('APP传过来的参数是', orderCode + '----' + money + '------'  + '----' + appid + '-----' + appsecret + '-----' + mchid + '-----' + mchkey);

        //首先生成签名sign
        // appid
        let mch_id = mchid;
        let nonce_str = wxMiniPayUnits.createNonceStr();
        let timestamp = wxMiniPayUnits.createTimeStamp();
        let body = '美术课件云助手';
        let out_trade_no = orderCode;
        let total_fee = wxMiniPayUnits.getmoney(money);
        let spbill_create_ip = req.connection.remoteAddress; // 支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP
        let notify_url = wxurl;
        let trade_type = 'JSAPI';  // 'APP';公众号：'JSAPI'或'NATIVE'

        let sign = wxMiniPayUnits.paysignjsapi(appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type, mchkey);

        // console.log('sign==', sign);

        //组装xml数据
        var formData = "<xml>";
        formData += "<appid>" + appid + "</appid>";  //appid
        formData += "<body><![CDATA[" + "美术课件云助手" + "]]></body>";
        formData += "<mch_id>" + mch_id + "</mch_id>";  //商户号
        formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串，不长于32位。
        formData += "<notify_url>" + notify_url + "</notify_url>";
        formData += "<openid>" + openid + "</openid>";
        formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";
        formData += "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>";
        formData += "<total_fee>" + total_fee + "</total_fee>";
        formData += "<trade_type>" + trade_type + "</trade_type>";
        formData += "<sign>" + sign + "</sign>";
        formData += "</xml>";

        //console.log('formData===', formData);

        var url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

        request({ url: url, method: 'POST', body: formData }, function (err, response, body) {
            if (!err && response.statusCode == 200) {
                console.log(body);

                xmlreader.read(body.toString("utf-8"), async function (errors, response) {
                    if (null !== errors) {
                        console.log(errors)
                        return;
                    }
                    console.log('长度===', response.xml.prepay_id.text().length);
                    var prepay_id = response.xml.prepay_id.text();
                    console.log('解析后的prepay_id==', prepay_id);


                    //将预支付订单和其他信息一起签名后返回给前端
                    let package = "prepay_id=" + prepay_id;
                    let signType = "MD5";
                    let minisign = wxMiniPayUnits.paysignjsapimini(appid, nonce_str, package, signType, timestamp, mchkey);

                    //创建单据
                    let course = await artPPTModel.findOne({
                        where: {
                            objectId: postData.pptId
                        },
                    })
                    course = Common.clone(course)

                    let orderParams = {
                        objectId: sid.uuid(),
                        out_trade_no: out_trade_no,
                        status: 0,
                        payMoney: Number(money),
                        storeMoney: (Number(money) * 0.8),
                        sellerId: course.userId,
                        buyerId: postData.uid,
                        type: 1,
                    }
                    
                    if (course) orderParams.pptId = course.objectId
                    await orderModel.order.create(orderParams)

                    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
                    returnData.data = {
                        'appId': appid,
                        'partnerId': mchid,
                        'prepayId': prepay_id,
                        'nonceStr': nonce_str,
                        'timeStamp': timestamp,
                        'package': 'Sign=WXPay',
                        'paySign': minisign,
                    }
                    return thisResponse.json(returnData);

                });
            }
        });
    })
}



//验证账单
async function checkOrder(req, thisResponse) {

    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['orderCode'], request);
    if (checkResult == false) return;

    //首先拿到前端传过来的参数
    let orderCode = postData.orderCode;

    let appid = wxConfig['wxMini' + postData.source].appId
    let mchid = wxConfig['wxMini' + postData.source].mchid
    let mchkey = wxConfig['wxMini' + postData.source].mchkey

    let nonce_str = wxMiniPayUnits.createNonceStr();
    let out_trade_no = orderCode;

    let sign = createSignV2({
        mch_id: mchid,
        appid: appid,
        out_trade_no: orderCode,
        nonce_str: nonce_str
    }, mchkey)

    //组装xml数据
    var formData = "<xml>";
    formData += "<appid>" + appid + "</appid>";  //appid
    formData += "<mch_id>" + mchid + "</mch_id>";  //商户号
    formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串，不长于32位。
    formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";
    formData += "<sign>" + sign + "</sign>";
    formData += "</xml>";

    var url = 'https://api.mch.weixin.qq.com/pay/orderquery';

    request({ url: url, method: 'POST', body: formData }, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            xmlreader.read(body.toString("utf-8"), async function (errors, response) {
                if (null !== errors) {
                    returnData.code = 0
                    returnData.msg = errors
                    return thisResponse.json(returnData);
                }

                if (response.xml.trade_state_desc.text() == "支付成功") {
                    let orderDet = await orderModel.order.findOne({
                        where: {
                            out_trade_no: orderCode
                        },
                    })

                    if (orderDet && orderDet.buyerId) {
                        //改变单据状态
                        await orderModel.order.update({
                            status: 1
                        }, {
                            where: {
                                objectId: orderDet.objectId,
                                out_trade_no: out_trade_no
                            }
                        })

                        returnData.msg = response.xml.trade_state_desc.text()
                        returnData.data = orderDet
                        return thisResponse.json(returnData);
                    }
                } else {
                    returnData.msg = response.xml.trade_state_desc.text()
                    return thisResponse.json(returnData);
                }
            })
        }
    });
}

//获取session
async function getSession(req, response) {
    let postData = req.body;
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let appid = wxConfig['wxMini' + postData.source].appId
    let appsecret = wxConfig['wxMini' + postData.source].secret

    let APPID = appid;
    let SECRET = appsecret;
    let CODE = postData.code;
    let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + APPID + '&secret=' + SECRET + '&js_code=' + CODE + '&grant_type=authorization_code'
    return request({ url: url, method: 'GET' }, async function (err, res, body) {
        body = JSON.parse(body);
        return body.openid
    })
}

// 加密签名
function createSignV2(info, key) {
    const hash = crypto.createHash("md5");
    let stringA = "";
    let keys = Object.keys(info);
    keys.sort();
    for (let item of keys) {
        stringA += `${item}=${info[item]}&`;
    }
    let stringSignTemp = `${stringA}key=${key}`;
    return hash.update(stringSignTemp).digest("hex");
}

